package com.dks.repository.impl.pay;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.dks.enumeration.PaymentEntityType;
import com.dks.mapper.PaymentRecordMapper;
import com.dks.models.pay.PaymentRecord;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;


/**
 * 调用微信接口
 * @author evan
 */
@Component
public class WXRequest {

    @Autowired
    private PaymentRecordMapper paymentRecordMapper;
    @Autowired
    private WxPayService wxPayService;


    /**
     * 统一下单
     * @author evan
     */
    public Object undifiedOrder(String description, String businessNum, Integer paymentBalance,
                               String openId, LocalDateTime date, long userId) throws WxPayException {
        WxPayUnifiedOrderRequest request = WxPayUnifiedOrderRequest.newBuilder()
                .body(description)
                .outTradeNo(businessNum)
                .totalFee(paymentBalance)
                .spbillCreateIp("127.0.0.1")
                .tradeType("JSAPI")
                .openid(openId)
                .build();
        Object order = wxPayService.createOrder(request);
        saveHistory(JSONObject.toJSONString(request), JSONObject.toJSONString(order), PaymentEntityType.CLASS_HOUR_PACKAGE, businessNum, userId, date);
        return order;
    }
//    public Map<String, String> undifiedOrder(String description, String businessNum, String paymentBalance,
//                                             Long payTimeSpanSec, String deviceInfo, String openId,
//                                             String spbillCreateIp, LocalDateTime date, long userId){
//        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
//        Map<String, String> data = new HashMap<>();
//        if (deviceInfo != null){
//            data.put(WXConstantValue.REQ_PARAM_UNIFIED_ORDER_DEVICE_INFO, deviceInfo);  //设备号
//        }
//        data.put(WXConstantValue.REQ_PARAM_UNIFIED_ORDER_BODY, description);  //商品描述
//        data.put(WXConstantValue.REQ_PARAM_UNIFIED_ORDER_OUT_TRADE_NO, businessNum);  // 商户订单号
////        data.put(WXConstantValue.REQ_PARAM_UNIFIED_ORDER_FEE_TYPE, WXConstantValue.CURRENCY_TYPE_CNY);  //货币类型
//        data.put(WXConstantValue.REQ_PARAM_UNIFIED_ORDER_TOTAL_FEE, paymentBalance);  //总金额
//        data.put(WXConstantValue.REQ_PARAM_UNIFIED_ORDER_SPBILL_CREATE_IP, spbillCreateIp);  //终端IP
//        data.put(WXConstantValue.REQ_PARAM_UNIFIED_ORDER_NOTIFY_URL, appPayNoticeUrl);  //通知地址
//        data.put(WXConstantValue.REQ_PARAM_UNIFIED_ORDER_TRADE_TYPE, WXConstantValue.WXPayTradeType.JSAPI.getType());  //支付类型 此处指定为小程序 JSAPI
//        data.put(WXConstantValue.REQ_PARAM_UNIFIED_ORDER_OPEN_ID, openId);  //支付类型 此处指定为小程序 JSAPI
//        data.put(WXConstantValue.WXPAY_COMMON_PARAM_NONCE_STR, WXPayUtil.generateNonceStr());  //随机字符串
//        if (payTimeSpanSec != null && payTimeSpanSec != 0){
//            data.put(WXConstantValue.REQ_PARAM_UNIFIED_ORDER_TIME_START, dtf.format(date));
//            data.put(WXConstantValue.REQ_PARAM_UNIFIED_ORDER_TIME_EXPIRE, dtf.format(date.plusMinutes(payTimeSpanSec))); //允许支付时间
//        }
//        try {
//            Map<String, String> resultMap = qswxPay.unifiedOrder(data);
//            saveHistory(data, resultMap, PaymentEntityType.CLASS_HOUR_PACKAGE, businessNum, userId, date);
//            return resultMap;
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * 调起支付接口
     * @author evan
     */
//    public String wxPaymentCallApp(String appId, String partnerid, String prePayId, String noncestr){
//        Map<String, String> ResultData = new HashMap<>();
//        ResultData.put(WXConstantValue.REQ_PARAM_PAYMENT_CALL_APPID, appId);
//        ResultData.put(WXConstantValue.REQ_PARAM_PAYMENT_CALL_PARTNERID, partnerid);
//        ResultData.put(WXConstantValue.REQ_PARAM_PAYMENT_CALL_PREPAYID, prePayId);
//        ResultData.put(WXConstantValue.REQ_PARAM_PAYMENT_CALL_PACKAGE, WXConstantValue.REQ_PARAM_PAYMENT_CALL_PACKAGE_VALUE);
//        ResultData.put(WXConstantValue.REQ_PARAM_PAYMENT_CALL_NONCESTR, noncestr);
//        ResultData.put(WXConstantValue.REQ_PARAM_PAYMENT_CALL_TIMESTAMP, String.valueOf(WXPayUtil.getCurrentTimestamp()));
//        try {
//            ResultData.put(WXConstantValue.REQ_PARAM_PAYMENT_CALL_SIGN, WXPayUtil.generateSignature(ResultData, qswxPayConfig.getKey(), WXPayConstants.SignType.HMACSHA256));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return JSONObject.toJSONString(ResultData);
//    }

//    /**
//     * 查询订单
//     * @author evan
//     */
//    public Map<String, String> orderQuery(PaymentOrder paymentOrder, Date date){
//        Map<String, String> data = new HashMap<>();
//        data.put("out_trade_no", paymentOrder.getBusinessOrderNum());
//        data.put("nonce_str", paymentOrder.getPaymentOrderNum());
//        try {
//            Map<String, String> resultMap = bfwxPay.orderQuery(data);
//            saveHistory(data, resultMap, BaseConstantValue.OPERATION_TYPE_ZF_5, BaseConstantValue.SYSTEM_USER_ID, date);
//            return resultMap;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//    /**
//     * 关闭订单
//     * @author evan
//     */
//    public Map<String, String> closeOrder(PaymentOrder paymentOrder, Date date){
//        Map<String, String> data = new HashMap<>();
//        data.put("out_trade_no", paymentOrder.getBusinessOrderNum());
//        data.put("nonce_str", paymentOrder.getPaymentOrderNum());
//        try {
//            Map<String, String> resultMap = bfwxPay.closeOrder(data);
//            saveHistory(data, resultMap, BaseConstantValue.OPERATION_TYPE_ZF_7, BaseConstantValue.SYSTEM_USER_ID, date);
//            return resultMap;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * 记录请求数据以及返回数据
     * @author evan
     */
//    public void saveHistory(Map<String, String> requestMap, Map<String, String> resultMap, PaymentEntityType entityType,
//                            String payBusinessNum, long userId, LocalDateTime date){
//        PaymentRecord paymentRecord = new PaymentRecord();
//        paymentRecord.setPayEntityType(entityType.name());
//        paymentRecord.setPayBusinessNum(payBusinessNum);
//        paymentRecord.setPayRequestInfo(JSONObject.toJSONString(requestMap));
//        paymentRecord.setPayResponseInfo(JSONObject.toJSONString(resultMap));
//        paymentRecord.setCreateUserId(userId);
//        paymentRecord.setGmtCreateTime(date);
//        paymentRecordMapper.insert(paymentRecord);
//    }

    public void saveHistory(String requestStr, String resultStr, PaymentEntityType entityType,
                            String payBusinessNum, long userId, LocalDateTime date){
        PaymentRecord paymentRecord = new PaymentRecord();
        paymentRecord.setPayEntityType(entityType.name());
        paymentRecord.setPayBusinessNum(payBusinessNum);
        paymentRecord.setPayRequestInfo(requestStr);
        paymentRecord.setPayResponseInfo(resultStr);
        paymentRecord.setCreateUserId(userId);
        paymentRecord.setGmtCreateTime(date);
        paymentRecordMapper.insert(paymentRecord);
    }




}
